#!/usr/bin/env python2

from __future__ import print_function

import sys

try:
    from pybtex.database.input.bibtex import Parser
    from pybtex.database.output.bibtex import Writer
    from pybtex.database import BibliographyData
except ImportError:
    print("""\
You need to install Pybtex [http://pybtex.sourceforge.net/] in order for this to work.
If you happen to be lucky and running Arch Linux the package is in AUR [http://aur.archlinux.org/packages.php?ID=47273]
""")
    sys.exit(1)


if len(sys.argv[1:]) != 2:
    print('Usage: python %s <input.bib> <output.bib>' % sys.argv[0])
    sys.exit(1)


bibin       = sys.argv[1]
bibout      = sys.argv[2]

parser      = Parser()
in_bibdata  = parser.parse_file(bibin)
out_bibdata = BibliographyData()


for counter, entry in enumerate(in_bibdata.entries.values()):

    try:
        first_author = entry.persons['author'][0]
        lastname     = first_author.last()[0]
        year         = entry.fields['year']
        key          = '%s:%s' % (lastname, year)
    except:
        print(entry)
        raise

    if key in set(out_bibdata.entry_keys):
        key = '%s%s' % (key, hex(counter).lstrip('0x'))

    out_bibdata.add_entry(key, entry)


writer = Writer()
writer.write_file(out_bibdata, bibout)
